import React, { useEffect, useMemo, useState } from 'react';
import { Tabs, Affix } from 'antd';
import loadable from '@loadable/component';

import { getKeyFromUrl } from '@/utils';
import { getCategoryStatusList, getMerchListByCategory } from '@/service/api';
import useDevice, { DEVICES } from '@/hooks/useDevice';
import styles from './Content.module.scss';

const List = loadable(() => import('@/pages/Fragment/List'));

export default props => {
    const initState = () => ({
        items: [],
        loading: false,
        pageNo: 1,
        pageSize: 12,
        total: 0,

        categories: [],
        categoryId: '',
    });
    const [state, setState] = useState(initState);
    const { nature, type } = props;
    const id = getKeyFromUrl('id');
    const deviceType = useDevice();

    // 获取谷子列表
    const getList = async (options={}) => {
      const { pageNo, pageSize, categoryId } = state;
      const idObj = {['work'===type?'seriesId':'charactarId']: id};
      const queryData = {pageNo, pageSize, nature, categoryId, ...idObj, ...options};

      setState(s => ({ ...s, loading: true }));
      try {
        const [res, err] = await getMerchListByCategory(queryData);
        if (err) return;
        const { records, current, total, size } = res?.data || {};
        const items = (1 === current ? [] : state.items).concat(records);
        setState(s => ({
            ...s,
            items,
            pageNo: current,
            pageSize: size,
            total,
            nature: queryData.nature,
        }));
      } finally {
        setState(s => ({ ...s, loading: false }));
      }
    };

    // 加载更多
    const onLoadMore = async () => {
        getList({ pageNo: state.pageNo + 1 });
    };

    // 切换分类
    const changeCategory = key => {
        setState(s => ({ ...s, categoryId: key }));
        getList({categoryId: key, pageNo: 1});
    };

    // 初始化
    const initData = async () => {
      const idObj = {['work'===type?'seriesId':'charactarId']: id};
      const [res, err] = await getCategoryStatusList({nature, ...idObj});
      if (err) return;
      const categories = res?.data || [];
      const categoryId = categories[0]?.categoryId || '';
      setState(o => ({...o, categories, categoryId}));
      getList({nature, categoryId, pageNo: 1});
    };

    useEffect(() => {
        initData();
    }, [nature]);

    return (
        <div className={styles['container']} style={{height: '100%', overflow:'hidden', '--tab-width': deviceType === DEVICES.MOBILE ? '80px' : '140px', '--tab-font-size': deviceType === DEVICES.MOBILE ? '12px' : '14px'}}>
          <div className={styles['tabs']}>
            {
              (state.categories || []).map(item => {
                return (
                  <div
                    key={item.categoryId}
                    className={`${styles['tab-item']} ${state.categoryId === item.categoryId ? styles['active'] : ''}`}
                    onClick={changeCategory.bind(null, item.categoryId)}
                  >
                    <>
                      <div className={styles['name']}>{item.categoryName}</div>
                      <div className={styles['count']}>{item.goodsCount}</div>
                    </>
                  </div>
                );
              })
            }
          </div>
          <div className={`${styles['tab-content']} ${deviceType === DEVICES.MOBILE ? styles['mobile'] : ''}`}>
            <List 
              type="tabmerch"
              dataSource={state.items}
              showMore={state.total && state.items?.length < state.total}
              onLoadMore={onLoadMore}
              loading={state.loading}
              grid={{ gutter: 12, xs: 2, sm: 2, md: 3, lg: 4, xl: 4, xxl: 4 }}
            />
          </div>
        </div>
    )
}
